

const ora = require("ora")//需要安装5.3.0版本，自带版本和最新版本可能有问题
const spinner = ora("正在准备发布项目");//引入这个主要是load转圈效果好看
const scpClient = require('scp2');
const chalk = require('chalk');//这个主要是改变console.log的颜色 ，截图中的success绿色和发布失败会显示红色字
const config = require('./upload.config/config');//引入服务器配置信息 带账号密码
const readline = require('readline');//读取输入，这个也是自带了
const fs = require("fs");
const dayjs = require("dayjs")//时间插件
let server = null;//定义了服务器信息变量
let modeStr = [];//   最终会是：test|prod61|prod60 
config.forEach(item => {
    modeStr.push(item.mode)
})




const addWaterMark = (val, callBack = Function) => {

    let scriptStr = `<script type="text/javascript" src='http://10.31.11.13:9787/watermark/js/partnerwebsite'></script>`
    if (val === 'test') {

    } else {
        scriptStr = `<script type="text/javascript" src='http://10.31.1.81:9787/watermark/js/partnerwebsite'></script>`
    }
    // 如果是测试环境，则修改index.html文件，插入测试环境水印
    fs.readFile('./build/index.html', 'utf-8', function (error, data) {
        // if (data) {
        //     if (data.indexOf('partnerwebsite') < 0) {
        //         const lastStr = '</html>';
        //         let newHtmlContent = `${data.split("</html>")[0]}${scriptStr}${lastStr}`
        //         fs.writeFile('./build/index.html', newHtmlContent, 'utf-8', () => {
        //             callBack();
        //         })
        //     }else{
        //         callBack();
        //     }

        // }
        callBack();
    })

}


const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})



function runQueLoop() {
    rl.question(`输入发布模式mode(${modeStr.join("|")}): `, val => {
        for (var i = 0; i < config.length; i++) {
            if (val === config[i].mode) {
                server = {
                    ...config[i]
                }

                break;
            }
        }
        addWaterMark(val, copyFile);

    })
}

rl.on('close', () => {
    process.exit(0)
})

runQueLoop()

var Client = require('ssh2').Client;


function copyFile() {
    spinner.start("正在准备中...");

    let pathArr = server.path.split('/'), rootFolder = pathArr[pathArr.length - 1];//获取根文件夹
    pathArr.pop();
    let rootPath = pathArr.join('/');
    const conn = new Client();
    const currTime = dayjs().format("YYYYMMDD")
    conn.on('ready', function () {
        spinner.start("正在发布...");
        conn.exec(`cd ${rootPath}\n
    mkdir ${rootFolder}_back${currTime}\n 
    cp -r ${rootFolder} ${rootFolder}_back${currTime}\n 
    rm -rf ${rootFolder}`, function (err, stream) {
            if (err) throw err;
            stream.on('close', function (code, signal) {
                // 在执行shell命令后，开始上传部署项目代码

                scpClient.scp(
                    './build',
                    {
                        host: server.host,
                        port: server.port,
                        username: server.username,
                        password: server.password,
                        path: server.path
                    },
                    function (err) {
                        spinner.stop();
                        if (err) {
                            console.log(err)
                            console.log(chalk.red('Fail! 发布失败.\n'));
                            rl.close();
                            throw err;
                        } else {
                            const str = `${server.name}，ip：${server.host}`
                            console.log(chalk.green('Success! 成功发布到' + str + '服务器! \n'));
                            rl.close();
                        }
                    }
                );
                conn.end();
            })
        });
    })
        .on('error', function (err) {
            console.log(chalk.red('Fail! 服务器连接失败.\n'));
            rl.close();
            throw err;
        })
        .connect({
            host: server.host,
            port: server.port,
            username: server.username,
            password: server.password
        });
}

